/*
  (C) 2007 - Boston University
  Contact: Michael Ocean 

	This class is taken directly from a CS511 submission

  This work is a part of the larger snBench project.  Information
  can be found at: http://csr.bu.edu/snbench 

  This program is free software; you can redistribute it and/or
  modify it under the terms of Version 2 of the GNU General Public 
  License.
  
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.
  
  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package stepide.xml;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathConstants;
import stepide.ErrorManager;

/**
	Overview: This class is analogous to .Net XmlNode class. It provides an easy way to evaluate
	XPath expressions against XML nodes
*/
public class XmlNode
{
	protected Node _node = null;

	protected XmlNode()
	{

	}
	
	public XmlNode(Node node)
	{
		_node = node;
	}

	/**
		Requires: XPath expression is expected to return multiple nodes
		Effects: evaluates the specified XPath expression on this XmlNode and returns all resulting nodes
	*/
	public NodeList selectNodes(String xPath) 
	{
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		NodeList nodes = null;
		try
		{
		        nodes = (NodeList) xpath.evaluate(xPath, _node, XPathConstants.NODESET);
		}
		catch(javax.xml.xpath.XPathExpressionException ex)
		{
			ErrorManager.LogError(ex);
		}
		return nodes;
	}

	/**
		Requires: XPath expression is expected to return a single node
		Effects: evaluates the specified XPath expression on this XmlNode and returns the resulting single node
	*/
	public Node selectNode(String xPath) 
	{
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		Node node = null;
		try
		{
		        node = (Node) xpath.evaluate(xPath, _node, XPathConstants.NODE);
		}
		catch(javax.xml.xpath.XPathExpressionException ex)
		{
			ErrorManager.LogError(ex);
		}
		return node;
	}
}